package com.ruoyi.framework.shiro.session;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.jedis.JedisConfig;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

import java.io.Serializable;


public class RedisSessionDao extends CachingSessionDAO {

    private static final String PREFIX = "SHIRO_SESSION_ID";



    private static final Logger LOGGER = LoggerFactory.getLogger(RedisSessionDao.class);

    @Override
    protected Serializable doCreate(Session session) {
        Serializable serializable = this.generateSessionId(session);
        assignSessionId(session, serializable);
        Jedis jedis = JedisConfig.getJedis();
        session.setTimeout(Constants.EXPRIE*1000);
        /*jedis.set(getByteKey(serializable),SerializationUtils.serialize((Serializable)session));
        jedis.expire(SerializationUtils.serialize(getByteKey(serializable)),EXPRIE);*/
        jedis.setex(getByteKey(serializable),Constants.EXPRIE, SerializationUtils.serialize((Serializable)session) );
        JedisConfig.closeJedis(jedis);
        return serializable;
    }


    @Override
    protected Session doReadSession(Serializable serializable) {
        if(serializable ==null){
            return null;
        }

        Jedis jedis = JedisConfig.getJedis();
        Session session = null;
        byte[] s = jedis.get(getByteKey(serializable));
        if (s != null) {
            session = SerializationUtils.deserialize(s);
            jedis.expire((PREFIX+serializable).getBytes(),Constants.EXPRIE);
        }
        JedisConfig.closeJedis(jedis);
        //判断是否有会话  没有返回NULL
        if(session==null){
            return null;
        }

        return session;
    }

    private byte[] getByteKey(Object k){
        if(k instanceof String){
            String key = PREFIX+k;
            return key.getBytes();
        }else {
            return SerializationUtils.serialize((Serializable) k);
        }
    }
    @Override
    protected void doUpdate(Session session) {
        if(session==null){
            return ;
        }
        Jedis jedis = JedisConfig.getJedis();
        session.setTimeout(Constants.EXPRIE*1000);
       /*jedis.set(getByteKey(session.getId()),SerializationUtils.serialize((Serializable)session));
       jedis.expire(SerializationUtils.serialize((PREFIX+session.getId())),EXPRIE);*/
        jedis.setex(getByteKey(session.getId()),Constants.EXPRIE, SerializationUtils.serialize((Serializable)session) );
        JedisConfig.closeJedis(jedis);

    }


    @Override
    protected void doDelete(Session session) {
        Jedis jedis = JedisConfig.getJedis();
        jedis.del(getByteKey(session.getId()));
        JedisConfig.closeJedis(jedis);

    }
}
